package com.jxbeidou.gateway.handler;

import com.jxbeidou.core.entity.R;
import com.jxbeidou.core.enums.ResultCode;
import com.jxbeidou.core.exception.ServerException;
import com.jxbeidou.gateway.entity.CaptchaVO;
import com.jxbeidou.gateway.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import jakarta.annotation.Resource;

/**
 * 验证码获取
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class ValidateCodeHandler implements HandlerFunction<ServerResponse> {
    @Resource
    private ValidateCodeService validateCodeService;

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest) {
        log.info("[ValidateCodeHandler]验证码获取事件");
        R<CaptchaVO> result = validateCodeService.createCaptcha();
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            return Mono.error(new ServerException("验证码生成错误"));
        }
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(result));
    }
}
